package com.tianji.learning.mq;

import com.tianji.api.dto.remark.LikedTimesDTO;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.CollUtils;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.service.IInteractionReplyService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaohai
 * @version 1.0
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class LikeTimesChangeListener {

    private final IInteractionReplyService replyService;


    // 交换机 队列 key

    /**
     * 收到点赞业务消息
     *
     * @param dtoList
     */
    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(name = "qa.liked.times.queue", durable = "true"),
                    exchange = @Exchange(name = MqConstants.Exchange.LIKE_RECORD_EXCHANGE, type = ExchangeTypes.TOPIC),
                    key = MqConstants.Key.QA_LIKED_TIMES_KEY
            )
    )
    public void listenLikeTimesChange(List<LikedTimesDTO> dtoList) {
        // 1.判断
        if (CollUtils.isEmpty(dtoList)) {
            return;
        }
        /*// 1.判断
        if (CollUtils.isEmpty(dtoList)) {
            return;
        }
        Map<Long, Integer> idLikeTimesMap = dtoList.stream()
                .collect(Collectors.toMap(LikedTimesDTO::getBizId, LikedTimesDTO::getLikedTimes));
        // 2.把dtoList转换为replyList
        Set<Long> replyIds = dtoList.stream().map(LikedTimesDTO::getBizId).collect(Collectors.toSet());
        List<InteractionReply> oldReplyList = replyService.getBaseMapper().selectBatchIds(replyIds);

        List<InteractionReply> replyList = new ArrayList<>();
        for (InteractionReply old : oldReplyList) {
            // 原有的点赞数 + dtoList里面的点赞数(id相同)
            InteractionReply reply = new InteractionReply();
            reply.setId(old.getId());
            reply.setLikedTimes(old.getLikedTimes() + idLikeTimesMap.get(old.getId()));

            replyList.add(reply);
        }

        replyService.updateBatchById(replyList);*/

        List<InteractionReply> replyList = new ArrayList<>();
        for (LikedTimesDTO dto : dtoList) {
            InteractionReply reply = new InteractionReply();
            reply.setId(dto.getBizId());
            reply.setLikedTimes(dto.getLikedTimes());
            replyList.add(reply);
        }
        // 3.批量更新
        replyService.updateBatchById(replyList);
    }
}
